<template>
  <div class="home-view">
    <!-- 轮播图 -->
    <div class="banner">
      <el-carousel height="400px">
        <el-carousel-item v-for="item in bannerList" :key="item.id">
          <img :src="item.imgUrl" :alt="item.title">
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 商品分类 -->
    <div class="category-section">
      <el-row :gutter="20">
        <el-col :span="4" v-for="category in categories" :key="category.id">
          <el-card class="category-item" shadow="hover">
            <img :src="category.icon" :alt="category.name">
            <span>{{ category.name }}</span>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 商品 -->
    <div class="hot-products">
      <h2>商品</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in hotProducts" :key="product.id">
          <el-card class="product-card" shadow="hover" @click="goToProductDetail(product.id)">
            <img :src="product.imgUrl || product.image" class="product-image" />
            <div class="product-info">
              <h3>{{ product.title || product.name }}</h3>
              <p class="price">¥{{ product.price }}</p>
              <el-button
                type="primary"
                size="small"
                @click="(event) => addToCart(product, event)"
              >
                加入购物车
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const hotProducts = ref([])
const categories = ref([])
const bannerList = ref([])

// 获取商品
const getHotProducts = async () => {
  try {
    const response = await axios.get('/logic/item/list', {
      params: {
        pageNum: 1,
        pageSize: 16
      }
    })
    // 直接使用返回的数据
    console.log('商品列表数据:', response.data) // 添加日志查看数据
    hotProducts.value = response.data
  } catch (error) {
    console.error('获取商品失败:', error)
    ElMessage.error('获取商品失败')
  }
}

// 获取商品分类
const getCategories = async () => {
  try {
    const response = await axios.get('/logic/category/list')
    categories.value = response.data
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 添加加入购物车方法
const addToCart = async (product, event) => {
  // 阻止事件冒泡，防止触发卡片的点击事件
  event.stopPropagation()
  // 检查是否登录
  const token = window.sessionStorage.getItem('tjpu22s10')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    await axios.post('/logic/cart/add', {
      itemId: product.id,
      quantity: 1
    })
    ElMessage.success('成功加入购物车')
  } catch (error) {
    console.error('加入购物车失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('加入购物车失败')
    }
  }
}

onMounted(() => {
  getHotProducts()
  getCategories()
})
</script>

<style scoped>
.home-view {
  width: 100%;
}

.banner {
  margin: 20px auto;
  max-width: 1200px;
}

.category-section {
  max-width: 1200px;
  margin: 40px auto;
}

.category-item {
  text-align: center;
  cursor: pointer;
}

.category-item img {
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
}

.hot-products {
  max-width: 1200px;
  margin: 40px auto;
}

.product-card {
  margin-bottom: 20px;
  cursor: pointer;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
}

.product-info h3 {
  margin: 10px 0;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}
</style>
